/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package repositoriodistribuido;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ylopez
 */
public class dmon {

    private static final int PORT = 43665;

    public dmon(int port) {
        try {
            dmonCommands c = new dmonCommandsImpl();
            Naming.rebind("rmi://localhost:"+ port +"/DmonService", c);
        } catch (Exception e) {
            System.out.println ("Trouble: " + e);
        }
    }

    public static void main(String args[]) throws RemoteException {
        int port = PORT;
        String userName = System.getProperty("user.name");

        try {
            if (args[0].equals("-p") && args.length == 2) {
                port = Integer.parseInt(args[1]);
            } else {
                System.err.println("Llamada a dmon inva'lida");
                    System.exit(-1);
            }
        } catch (NumberFormatException nfe) {
            //TODO Manejar esta excepcion bien
            System.err.println("El puerto no es un nu'mero entero.");
            nfe.printStackTrace();
            System.exit(-1);
        }

        System.out.println("Puerto local: " + port);

        java.rmi.registry.LocateRegistry.createRegistry(port);
        new dmon(port);

        System.out.println("Escriba Bye para salir");
        System.out.print(userName + "$> ");
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromUser;
        String[] commandLine;
        String[] results;
        dmonCommandsImpl dci = new dmonCommandsImpl();
        try {
            fromUser = stdIn.readLine();
            while (fromUser != null) {
                commandLine = fromUser.split(" ");
                if (commandLine[0].equals("tuser")) {
                    results = dci.tuser();
                    dmonCommandsImpl.printResoults("tuser", results);
                } else if (commandLine[0].equals("ndrep")) {
                    results = dci.ndrep();
                    dmonCommandsImpl.printResoults("ndrep", results);
                } else if (commandLine[0].equals("nops")) {
                    results = dci.nops();
                    dmonCommandsImpl.printResoults("nops", results);
                } else if (commandLine[0].equals("Bye")) {
                    System.exit(0);
                } else {
                    System.err.println("Comando: "+ commandLine[0] +" invalido.");
                }
                System.out.print(userName + "$> ");
                fromUser = stdIn.readLine();
            }
            stdIn.close();
        } catch (IOException ex) {
            Logger.getLogger(dcli.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
